import { asyncRoutes, constantRoutes, previewRoutes } from '@/router'
import { getAuthsTree } from '@/views/tmpt/auth/api/auth.js'
/* Layout */
// import Layout from '@/layout'
// import TmptPreview from '@/views/tmpt/tmpt-preview'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: [],
  routerCrumbList: []
}

const mutations = {
  SET_PRE_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_ROUTES: (state, routes) => {
    state.addRoutes = state.addRoutes.concat(routes)
    state.routes = state.routes.concat(routes)
  },
  Clear_Routes: (state) => {
    state.routes = []
    state.addRoutes = []
  },
  SET_CrumbList: (state, routerCrumbList) => {
    state.routerCrumbList = routerCrumbList
  },
}

import Vue from 'vue'
import TmptPreview from '@/views/tmpt/tmpt/tmpt-preview.vue';

const actions = {
  clearRoutes({ commit } ) {
    commit('Clear_Routes')
  },
  generatePreviewRoutes({ commit }, roles) {
    const preview_menu_id = 667
    return new Promise(resolve => {
      getAuthsTree({ id: preview_menu_id }).then(result => {
        if (result.success) {
          // 重新登录时，state中可能有上次保留的数据，先清空一下
          previewRoutes[0].children.splice(0)
          // read the new routes
          const previewAuths = result.map.list
          previewAuths.forEach((auth) => {
            const route = {}
            route.path = auth.name

            //  create module dynamic
            Vue.component("app", {
              name:'Tmpt-Preview-' + auth.name,
              props: {
                keyRandomProp: String
              },
              data: function() {
                return {
                  keyRandom: ''
                };
              },
              template:
                '<div><div id="appId"/> </div>',

              watch: {
                keyRandomProp() {
                  this.keyRandom = this.keyRandomProp
                }
              },
              mounted() {
                this.keyRandom = this.$route.query.keyRandom
                if (this.keyRandom === undefined) {
                  this.keyRandom = this.keyRandomProp
                }
                this.insert()
              },
              methods: {
                insert() {
                  const bcConstructor = Vue.extend(TmptPreview);
                  const instance = new bcConstructor({
                    propsData:{
                      keyRandomProp: this.keyRandom
                    }
                  });
                  instance.$mount('#appId');
                }
              }
            });


            route.component = Vue.component("app");
            route.param = { keyRandom: auth.url }
            route.name = 'Tmpt-Preview-' + auth.name // 与@/views/tmpt/tmpt-preview中设置的name对应
            // route.name = 'Tmpt-Preview' // 与@/views/tmpt/tmpt-preview中设置的name对应
            route.meta = {
              title: auth.name,
              icon: 'table',
              roles: ['tmpt:query'],
              cache: true
            }
            previewRoutes[0].children.unshift(route)
          })

          const previewRoutesFinal = filterAsyncRoutes(previewRoutes, roles)
          commit('SET_PRE_ROUTES', previewRoutesFinal)
          resolve(previewRoutes)
        }
      })
    })
  },

  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      /* if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }*/
      accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },

  setCrumbList({ commit }, routerCrumbList) {
    commit('SET_CrumbList', routerCrumbList)
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
